package com.example.ec.controller;

import com.example.ec.model.User;
import com.example.ec.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("user")
public class UserController extends BaseController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value = "signIn",method = RequestMethod.POST)
    private String signIn(User user) {
        user = userService.queryOne("queryUserByNameAndPassword", user);
        if (user == null) {
            request.setAttribute("error", "用户名或密码错误");
            return "index.jsp";
        }
        session.setAttribute("user", user);
        if (user.getRole() == 0) {
            return "redirect:/user/home.jsp";
        } else {
            session.setAttribute("user",userService.queryList("queryAllUsers",null));
            return "redirect:/admin/admin.jsp";

        }
    }

    @RequestMapping(value = "signUp",method = RequestMethod.POST)
    private String signUp(User user){
        if (userService.queryOne("queryUserByName",user) != null){
            request.setAttribute("error","用户名已存在!");
            return "/sign_up.jsp";
        }
        userService.create(user);
        return "redirect:/index.jsp";
    }
}
